import {
    Node, MeshRenderer, gfx, Color, Vec3, renderer,
    RenderTexture, IRectLike, ImageAsset, Texture2D
} from "cc";

/**
 * 使用（取消）直线网格绘制物体
 * @param target 节点或网格组件
 * @param recover 恢复
 * @param color 绘制颜色，默认绿色
*/
export function linearizeMesh(target: Node | MeshRenderer, recover: false): void;
export function linearizeMesh(target: Node | MeshRenderer, color?: Color): void;
export function linearizeMesh(target: Node | MeshRenderer, opt?: false | Color): void {
    const mesh = target instanceof Node ? target.getComponent(MeshRenderer) : target;
    const mat = mesh?.material as renderer.MaterialInstance, pass0 = mat?.passes[0];
    if (!pass0) return;
    if (opt === false) {
        pass0['_primitive'] = gfx.PrimitiveMode.TRIANGLE_LIST;
        mat.setProperty('albedoScale', Vec3.ONE);
    } else {
        pass0['_primitive'] = gfx.PrimitiveMode.LINE_STRIP;
        mat.setProperty('albedoScale', opt ?? Color.GREEN);
    }
    mat.onPassStateChange(false);
}

/**
 * 使用渲染纹理的一部分创建2D纹理
 * @param from 渲染纹理
 * @param rect 指定区域
 * @return 生成的材质
*/
export function copyRenderToTex2D(from: RenderTexture, rect?: IRectLike): Texture2D {
    let x = rect?.x ?? 0, y = rect?.y ?? 0, { width, height } = rect ?? from;
    const buf = from.readPixels(x, y, width, height);
    const img = new ImageAsset(), tex = new Texture2D;
    img.reset({ _data: buf, width, height, format: Texture2D.PixelFormat.RGBA8888, _compressed: false });
    tex.image = img;
    return tex;
}